<template>
    <!-- 标题 -->
    <van-nav-bar
        title="用户登录"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />


    <div class="v-photo">
                <van-image src="https://img.zcool.cn/community/01f8b6593a0054a8012193a31c86c5.jpg@2o.jpg" />
            </div>
    <!-- 账户登录 -->
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="username"
                name="账号"
                label="账号"
                placeholder="账号"
                :rules="[{ required: true, message: '请填写账号' }]"
            />
            <van-field
                v-model="password"
                type="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref, type Ref } from 'vue'
import { RequestLogin } from '@/api/index'
import { useAccountStore } from '@/stores/user'
import type { IAccount } from '@/types/types'
import {useRouter} from 'vue-router'
import {Toast} from 'vant'


// 返回上一级
const onClickLeft = () => history.back()

// 登录
const username: Ref<string> = ref('')
const password: Ref<string> = ref('')
const accountStore = useAccountStore()
const router = useRouter()
const onSubmit = async () => {
    const data = await RequestLogin(username.value, password.value)
    const { resultCode, resultInfo, token } = data
    if (resultCode === 1) {
        //保存用户信息，主界面登录按钮换成头像
        const actions: IAccount = {
            id: resultInfo.uid,
            nick: resultInfo.nick,
            url: resultInfo.headerimg,
        }
        accountStore.saveAccount(actions)
        //保存token
        localStorage.setItem('TOKEN', token as any)
        // accountStore.token = token
        // console.log(accountStore.token);
        
      
        
        //登录成功，页面跳转
        Toast.success('登录成功！')
        router.replace('/')
    }else{
        Toast.fail('账号或密码错误')
    }
}
</script>

<style scoped></style>
